package com.tjh.springbootapi.config;

import com.koala.apiprototype.redis.RedisStringService;
import com.tjh.springbootapi.common.ApiConstants;
import com.tjh.springbootapi.view.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求上下文拦截器
 * Create by koala on 2019-12-31
 */

public class RequestContextInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisStringService redisStringService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(ApiConstants.HEADER_API_TOKEN);
        UserToken userInfoView;
        /*if ("dev".equalsIgnoreCase(token)) {
            //TODO 开发自动登录用，发布前要删除！！！
            userInfoView = new UserToken();
            userInfoView.setToken("dev");
        } else {
            userInfoView = redisStringService.getValue(ApiConstants.REDIS_KEY_USER_TOKEN_PREFIX + token, UserToken.class);
        }*/
        //TODO 开发自动登录用，发布前要删除！！！
        userInfoView = new UserToken();
        userInfoView.setToken("dev");
        ApiRequestContext.init(request, userInfoView);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程变量
        ApiRequestContext.clear();
        super.afterCompletion(request, response, handler, ex);
    }
}
